﻿using AutoTest.Business.Dto.AdminUser;
using AutoTest.Business.IServices;
using AutoTest.Business.IServices.Common;
using AutoTest.Business.Vo.AdminUser;
using AutoTest.Domain.Entities;
using AutoTest.Domain.Enums;
using AutoTest.Framework.Exceptions;
using AutoTest.Framework.Ioc;
using Mapster;
using SqlSugar;

namespace AutoTest.Business.Services
{
    /// <summary>
    /// 后台用户服务
    /// </summary>
    public class AdminUserService(ISqlSugarClient db,IJwtService jwtService) : IAdminUserService, IScoped
    {
        private readonly ISqlSugarClient _db = db;
        private readonly IJwtService _jwtService = jwtService;


        /// <summary>
        /// 后台用户登录
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns></returns>
        public async Task<AdminLoginVo> LoginUser(AdminUserLoginDto loginDto)
        {
            var adminUser = (await _db.Queryable<AdminUser>().FirstAsync(t =>
                                                t.UserName == loginDto.UserName
                                          && t.Password == loginDto.Password
                                          && t.Status == EnumStatus.Enable
                                                )) ?? throw new BusinessException("用户名或者密码错误");
            var vo = adminUser.Adapt<AdminLoginVo>();

            vo.Token = _jwtService.Generate(vo);
            return vo;
        }

    }
}
